<?php
/*
 * description：
 * author：wh
 * email：
 * createTime：{2023/12/20} {15:52} 
 */

namespace wanghua\general_utility_tools_php\wechat;


use wanghua\general_utility_tools_php\tool\Tools;

class WechatMsgPush
{
    protected $token = 'qwer';
    //protected $logicObject = null;
    public function __construct($token)
    {
        $this->token = $token;
        //$this->logicObject = $logicObject;
    }

    /**
     * desc：微信消息推送入口
     *
     *
     * 微信消息入口只有一个，所有的消息推送都会POST到这个入口
     *
     * author：wh
     * @return string
     */
    //function msg(){
    //    //Tools::log_to_write_txt(['微信推送消息.'=>input()]);
    //
    //    $this->logicObject->run();
    //
    //    return $this->checkSignature();
    //}

    /**
     * desc：接入微信（小程序、小游戏）消息推送服务
     *
     * https://developers.weixin.qq.com/minigame/dev/guide/open-ability/message-push.html#option-url
     *
     * 使用方法：
     *
     *  //微信消息推送入口（消息推送唯一入口）
     *  function msg(){
            //入参：{"signature":"78c3552749bdc470d8c13387ceef1ea6c5c5423a","timestamp":"1705482487","nonce":"776591758","ToUserName":"gh_d50089f85963","FromUserName":"oOkYN5aDkdRQWe_b3yKVXzKm7fZM","CreateTime":1705482487,"MsgType":"event","Event":"minigame_deliver_goods","MiniGame":{"OrderId":"b09c1097-c7cc-4872-ba32-352b3c205e61","IsPreview":1,"ToUserOpenid":"oOkYN5cLG1MKjjVYrRPZwirFnw-c","GoodsList":[{"Id":"10001","Num":1}],"Zone":1001,"SendTime":1705482487}}

            $MsgType = input('MsgType');
            $Event = input('Event');
            //根据消息类型和事件类型进行不同的业务逻辑处理
            if($MsgType == 'event' && $Event=='minigame_deliver_goods'){
                //这里要注意一个问题，input获取MiniGame会报错，原因不明，只有换一种方式获取：$all_post = input();
                $this->sendMiniGameGiftOrder($all_post);//发送小游戏礼包
                return 'success';//推荐
            }
            //验签，验证是否是微信发来的消息
            return $this->checkSignature();
        }
     *
     * author：wh
     * @return bool
     */
    function checkSignature()
    {
        $echostr = input('echostr');
        $signature = input('signature');//$_GET["signature"];
        $timestamp = input('timestamp');//$_GET["timestamp"];
        $nonce = input('nonce');//$_GET["nonce"];

        $token = $this->token;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if ($tmpStr == $signature ) {
            return $echostr;//原样返回
        } else {
            return 'fail';
        }
    }

//    function pushmsg(){
//        $root_path = Tools::get_root_path();
//
//        include_once "D:\wanghua\projects\break_mini_game_admin\data\wechat_msg_demo\wxBizMsgCrypt.php";
//
//// 第三方发送消息给公众平台
//        $encodingAesKey = "k46Mhu1tgHFExrSrRPptKG0CltKFEn2EFocMT1tRbS6";
//        $token = $this->token;
//        $timeStamp = time();
//        $nonce = "qwer";
//        $appId = "wx5d121791c36c2fe3";
//        $text = "<xml><ToUserName><![CDATA[oia2Tj我是中文jewbmiOUlr6X-1crbLOvLw]]></ToUserName><FromUserName><![CDATA[gh_7f083739789a]]></FromUserName><CreateTime>1407743423</CreateTime><MsgType><![CDATA[video]]></MsgType><Video><MediaId><![CDATA[eYJ1MbwPRJtOvIEabaxHs7TX2D-HV71s79GUxqdUkjm6Gs2Ed1KF3ulAOA9H1xG0]]></MediaId><Title><![CDATA[testCallBackReplyVideo]]></Title><Description><![CDATA[testCallBackReplyVideo]]></Description></Video></xml>";
//
//
//        $pc = new \WXBizMsgCrypt($token, $encodingAesKey, $appId);
//        $encryptMsg = '';
//        $errCode = $pc->encryptMsg($text, $timeStamp, $nonce, $encryptMsg);
//        if ($errCode == 0) {
//            print("加密后: " . $encryptMsg . "\n");
//        } else {
//            print($errCode . "\n");
//        }
//
//        $xml_tree = new \DOMDocument();
//        $xml_tree->loadXML($encryptMsg);
//        $array_e = $xml_tree->getElementsByTagName('Encrypt');
//        $array_s = $xml_tree->getElementsByTagName('MsgSignature');
//        $encrypt = $array_e->item(0)->nodeValue;
//        $msg_sign = $array_s->item(0)->nodeValue;
//
//        $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
//        $from_xml = sprintf($format, $encrypt);
//
//// 第三方收到公众号平台发送的消息
//        $msg = '';
//        $errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
//        if ($errCode == 0) {
//            print("解密后: " . $msg . "\n");
//        } else {
//            print($errCode . "\n");
//        }
//    }
}